extends Control

@onready var label = $Label
@onready var gameEndPanel = $GameEnd
@onready var gameEndPanelScoreLabel = $GameEnd/HBoxContainer/ScoreLabel
@onready var exitGameToast = $ExitGameToast
@onready var uploadScoreButton = $GameEnd/BottomButtons/UploadScore

func _ready():
	GlobalSignals.UPDATE_SCORE_VIEW.connect(UPDATE_SCORE_VIEW_handler)
	GlobalSignals.NM_UPLOAD_SCORE_RESULT.connect(NM_UPLOAD_SCORE_RESULT_handler)


func _exit_tree():
	GlobalSignals.UPDATE_SCORE_VIEW.disconnect(UPDATE_SCORE_VIEW_handler)
	GlobalSignals.NM_UPLOAD_SCORE_RESULT.disconnect(NM_UPLOAD_SCORE_RESULT_handler)


func gameEnd():
	showGameEndPanel()


func NM_UPLOAD_SCORE_RESULT_handler(data):
	uploadScoreButton.text = "已上传"
	uploadScoreButton.disabled = true


func showExitGameToast():
	exitGameToast.visible = true
	

func hideExitGameToast():
	exitGameToast.visible = false


func showGameEndPanel():
	gameEndPanel.visible = true
	gameEndPanelScoreLabel.text = label.text
	uploadScoreButton.text = "上传得分"
	uploadScoreButton.disabled = false
	
	
func hideGameEndPanel():
	gameEndPanel.visible = false


func UPDATE_SCORE_VIEW_handler():
	setScore(Global.score)


func setVisible(b):
	visible = b

	
func setScore(number):
	label.text = "得分：" + str(number)


func _on_upload_score_pressed():
	GlobalSignals.PLAY_SOUND.emit(SoundManager.CLICK)
	NetMessages.uploadScore()


func _on_exit_game_pressed():
	GlobalSignals.PLAY_SOUND.emit(SoundManager.CLICK)
	showExitGameToast()
	

func _on_force_return_pressed():
	_on_return_pressed()


func _on_return_pressed():
	GlobalSignals.PLAY_SOUND.emit(SoundManager.CLICK)
	hideExitGameToast()
	hideGameEndPanel()
	
	Global.changeScene("Title")
